package io.renren.modules.yckj.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.yckj.dto.TeamRelationDTO;
import io.renren.modules.yckj.entity.TeamRelationEntity;
import io.renren.modules.yckj.excel.TeamRelationExcel;
import io.renren.modules.yckj.service.TeamRelationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 课题组管理关系表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2025-04-28
 */
@RestController
@RequestMapping("yckj/teamrelation")
@Tag(name = "课题组管理关系表")
public class TeamRelationController {
    @Autowired
    private TeamRelationService teamRelationService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")
    })
    @RequiresPermissions("yckj:team:page")
    public Result<PageData<TeamRelationDTO>> page(@RequestParam Map<String, Object> params) {
        PageData<TeamRelationDTO> page = teamRelationService.page(params);

        return new Result<PageData<TeamRelationDTO>>().ok(page);
    }

    @GetMapping("list")
    @Operation(summary = "列表")
    @Parameters({
            @Parameter(name = "teamId", description = "课题组Id", in = ParameterIn.QUERY, required = true, ref = "long"),
            @Parameter(name = "userId", description = "用户Id", in = ParameterIn.QUERY, required = true, ref = "long")
    })
//    @RequiresPermissions("yckj:team:page")
    public Result<List<TeamRelationDTO>> list(@RequestParam Map<String, Object> params) {
        List<TeamRelationDTO> list = teamRelationService.list(params);
        return new Result<List<TeamRelationDTO>>().ok(list);
    }


    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("yckj:team:info")
    public Result<TeamRelationDTO> get(@PathVariable("id") Long id) {
        TeamRelationDTO data = teamRelationService.get(id);

        return new Result<TeamRelationDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    @RequiresPermissions("yckj:team:save")
    public Result save(@RequestBody TeamRelationDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        TeamRelationEntity teamRelation = teamRelationService.getByTeamIdAndUserId(dto.getTeamId(), dto.getUserId());
        if (teamRelation == null) {
            teamRelationService.save(dto);
        } else {
            return new Result().error(1, "当前用户已添加");
        }
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    @RequiresPermissions("yckj:team:update")
    public Result update(@RequestBody TeamRelationDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        TeamRelationDTO teamRelationDTO = teamRelationService.get(dto.getId());
        if (teamRelationDTO != null) {
            if (teamRelationDTO.getDebtLimitUse().compareTo(BigDecimal.ZERO) > 0) {
                return new Result().error(1, "当前用户有欠款，不能修改");
            } else {
                teamRelationService.update(dto);
                return new Result();
            }
        } else {
            return new Result().error(1, "此记录不存在");
        }
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除")
    @RequiresPermissions("yckj:team:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        for (Long id : ids) {
            TeamRelationDTO teamRelationDTO = teamRelationService.get(id);
            if (teamRelationDTO != null) {
                if (teamRelationDTO.getDebtLimitUse().compareTo(BigDecimal.ZERO) > 0) {
                    return new Result().error(1, "当前用户有欠款，不能删除");
                } else {
                    teamRelationService.deleteById(id);
                    return new Result();
                }
            } else {
                return new Result().error(1, "此记录不存在");
            }
        }
        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    @RequiresPermissions("yckj:team:export")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<TeamRelationDTO> list = teamRelationService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "课题组管理关系表", list, TeamRelationExcel.class);
    }

}